//
//  ZyNetWork.swift
//  SwiftLearnAll
//
//  Created by iosdev1 on 2017/7/31.
//  Copyright © 2017年 ygsoft. All rights reserved.
//

import UIKit

enum HTTPRequestMethod {
    case GET
    case PUT
    case POST
    case DELETE
    case PATCH
    case HEAD
}

class ZyNetWork: NSObject {

    class func httpRequestTask(method:HTTPRequestMethod, url:String, parameters:String, error:Bool, SuccessClosure:@escaping (_ responseData:Any)->Void, FailClosure:@escaping (_ error:Error)->Void) -> Void {
        //创建会话对象
        let session: URLSession = URLSession.shared
        //根据会话对象创建task
        let url: NSURL = NSURL(string: url)!
        //创建可变的请求对象
        let request: NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
        let r_success:(_ data:Data?, _ responseObject:URLResponse?, _ errorInfo:Error?) ->Void = {(data:Data?, responseObject:URLResponse?, errorInfo:Error?)in
            if(errorInfo == nil){
            //解析数据
            //说明：（此处返回的数据是JSON格式的，因此使用NSJSONSerialization进行反序列化处理）
                do {
                    let dict  = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.init(rawValue: 0))
                    SuccessClosure(dict)
                } catch {
                    zyUIshowMessage(message: "数据解析失败");
                }
            }else {
                FailClosure(errorInfo!)
            }
        }
        switch method {
        case HTTPRequestMethod.GET:
            break
        case HTTPRequestMethod.POST:
            //修改请求方法为POST
            request.httpMethod = "POST"
            request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            //设置请求体
            request.httpBody = parameters.data(using: String.Encoding.utf8)
            //根据会话对象创建一个Task(发送请求）
//            let dataTask:URLSessionDataTask = session.dataTask(with: request as URLRequest, completionHandler: r_success)
//            //执行任务
//            dataTask.resume()
            break
        case HTTPRequestMethod.DELETE: break

        case HTTPRequestMethod.PUT: break

        case HTTPRequestMethod.PATCH: break

        case HTTPRequestMethod.HEAD: break
        }
        let dataTask:URLSessionDataTask = session.dataTask(with: request as URLRequest, completionHandler: r_success)
        //执行任务
        dataTask.resume()
    }
}
